package org.logistics;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.logistics.bean.ReplayPathBean;
import org.logistics.tools.RequestToHistoryThread;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.Geometry;
import com.baidu.mapapi.map.Graphic;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.utils.CoordinateConvert;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.platform.comapi.basestruct.GeoPoint;


/**
 * 
 * @author L_G-TIM
 *根据接口返回的历史轨迹点，绘制出车辆指定时间段的行走轨迹
 */
public class PlayBackHistoryPathActivity extends Activity{
	
	/**
	 * 作为标志，记录提交后修改那个部分的代码
	 * 过滤轨迹点的算法还有待改进、历史轨迹点的播放效果希望弄成动画、
	 * 显示轨迹点当时的状态（有否超速等等）
	 */
	private static final String FLAG = "ProgrammingPlace";
	/**
	 * 打印日志的标志
	 */
	private static final String TAG = "PlayBackHistoryPathActivity";
	/**
	 * 百度地图的密钥
	 */
//	private static final String MAP_KEY = "WWoClXrViPu4LkGyECM4kyjL";
	/**
	 * 管理对象
	 */
	private BMapManager mBMapMan = null;
	/**
	 * 百度地图控件对象
	 */
	private MapView mMapView = null;
	/**
	 * 用于控制百度地图
	 * 得到mMapView的控制权,可以用它控制和驱动平移和缩放 
	 */
	private MapController mMapController = null;
	/**
	 * 播放历史轨迹的按钮
	 */
	private Button mReplayButton = null;
	/**
	 * 设置起止时间按钮
	 */
	private Button mSetDateTimeButton = null;
	/**
	 * 返回到汽车列表按钮
	 */
	private ImageButton backButton = null;
	/**
	 * 过滤后的历史轨迹点集合
	 */
	//private List<GeoPoint> pointList = null;
	/**
	 * 过滤后，历史轨迹点对象集合
	 */
	private List<ReplayPathBean> rpbList = null;
	/**
	 * 请求历史轨迹接口后，取得的轨迹点
	 */
	/**
	 * 调用此Activity的Intent对象，本程序为List的Intent对象
	 */
	private Intent listIntent = null;
	
	/**
	 * 提示消息
	 */
	private Toast mToast = null;
	
	//与设置时间的Dialog相关的
	/**
	 * SetDateTimeDialog
	 */
	private EditText stTimeEditor = null;
	private EditText enTimeEditor = null;
	private EditText stDateEditor = null;
	private EditText enDateEditor = null;
	
	/**
	 * 请求接口子线程构造函数的参数
	 */
	//开始时间
	String stDateTime = null;
	//结束时间
	String enDateTime = null;
	//车辆IMEI，唯一标识
	String IMEI = null;
	Calendar calendar = null;
	
	//与子线程相关的
	/**
	 * 
	 */
	private MyHandler mHandler = null;
	/**
	 * handler Message.what
	 * 线程消息what
	 */
	private final int REPLAY = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//注意：请在试用setContentView前，初始化BMapManager对象，否则会报错。
/*		mBMapMan = new BMapManager(getApplication());
		mBMapMan.init(MAP_KEY, new MKGeneralListener() {
		    //校验Key是否有效
			@Override
			public void onGetPermissionState(int iError) {
				if(iError == MKEvent.ERROR_PERMISSION_DENIED) {
					showToast("API KEY 错误，请检查");
				}
			}
			//网络状况
			@Override
			public void onGetNetworkState(int iError) {
				if(iError == MKEvent.ERROR_NETWORK_CONNECT){
					showToast("您的网络出错啦！");
				}
			}
		});*/
		
		setContentView(R.layout.activity_replay_path_map);
		
		mMapView = (MapView)findViewById(R.id.replayMapView);
		//显示内置缩放控件
		mMapView.setBuiltInZoomControls(true);
		
	    mMapController = mMapView.getController();
		//设置地图是否响应点击事件
	//	mMapController.enableClick(true);
		//设置地图缩放级别
		mMapController.setZoom(16);

		/**
		 * 设定地图初始化中心
		 */
		listIntent = getIntent();
		IMEI = listIntent.getStringExtra("IMEI");
		double mLat = listIntent.getDoubleExtra("mLat", 22.895429773083851);
       	double mLon = listIntent.getDoubleExtra("mLon", 112.85362780094147);
       	Log.d(TAG, mLat + "");
       	Log.d(TAG, mLon + "");
	   	int lat = (int) (mLat*1E6);
	   	int lon = (int) (mLon*1E6);
	   	GeoPoint point = new GeoPoint(lat, lon);
	   	point = CoordinateConvert.fromWgs84ToBaidu(point);
	   	mMapController.setCenter(point);
	   	
		// 清理前一次的图层
	//	mMapView.getOverlays().clear();
		mMapView.refresh();
		// 刷新控件，android的函数
		mMapView.invalidate();
		
		Log.d(TAG, "init here is "+  Thread.currentThread().getName());
		// 在主线程中创建Handler ，此Handler与主线程进行了绑定  
		mHandler = new MyHandler();
		
		/**
		 * 获取顶部工具栏的按钮控件
		 */
		backButton = (ImageButton)findViewById(R.id.back_button);
		mReplayButton = (Button)findViewById(R.id.play_path_button);
		mSetDateTimeButton = (Button)findViewById(R.id.set_time_button);
		/**
		 * 为顶部工具栏绑定监听器
		 */
		backButton.setOnClickListener(new MyButtonListener());
		mReplayButton.setOnClickListener(new MyButtonListener());
		mSetDateTimeButton.setOnClickListener(new MyButtonListener());
		
	}
	
	/**
	 * Handler类，
	 * handlerMessage方法，处理子线程的handler.sendMessage(msg);
	 * @author L_G-TIM
	 *
	 */
	private class MyHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case REPLAY:
				JSONArray rootResults = (JSONArray)msg.obj;
				if (rootResults != null) {
					// makeReplayPath(rootResults);
					Log.d(TAG, "return to handleMessage "+  Thread.currentThread().getName());
					Log.d(TAG, "rootResults is " + rootResults);
					filterForRootJson(rootResults);
					makeReplayPath();
				}
				break;

			default:
				break;
			}
			Log.d(TAG, "子线程返回的消息：" + msg);
		}
		
	}
	
	/**
	 * 过滤掉相近重复的轨迹点，并构造pointList
	 * 根据距离、时间间隔来判断
	 * @param rootResults
	 */
	public void filterForRootJson(JSONArray rootResults)
	{
	//	pointList = new ArrayList<GeoPoint>();
		rpbList = new ArrayList<ReplayPathBean>();

		double mLat = 0.0;
		double mLon = 0.0;
		int lat = 0;
		int lon = 0;
		GeoPoint point = null;
		ReplayPathBean rpb = null;

		// 把所有的历史轨迹点，装入pointList中
				//ProgrammingPlace1
				try {
					int rl = rootResults.length();
					Log.d(TAG, "rootResults is " + rootResults);
					int hasAdd = 0;
					//判断历史轨迹点的个数，如果点少于两个，则认为是没有轨迹
					if (rl < 2) {
						showToast("没有数据！");
					}
					else {
						for (int i = 0; i < rl; i++) {
							mLat = rootResults.getJSONObject(i).getDouble("Lat");
							mLon = rootResults.getJSONObject(i).getDouble("Lng");
							lat = (int) (mLat * 1E6);
							lon = (int) (mLon * 1E6);
							point = new GeoPoint(lat, lon);
							rpb = new ReplayPathBean();

							if (i == 0) {
								hasAdd++;
							//	pointList.add(point);
								rpb.setDirect(rootResults.getJSONObject(i).getInt("Direct"));
								rpb.setLat(mLat);
								rpb.setLng(mLon);
								rpb.setSpeed(rootResults.getJSONObject(i).getDouble("Speed"));
								rpb.setPoint(point);
								rpbList.add(rpb);
							} else if (i > 0) {
								//根据两个轨迹点之前的距离和相隔的时间过滤,CollectTime":"\/Date(1384107982643+0800)时间单位为毫秒
								Log.d(TAG, "hasAdd == " + hasAdd);
								double distance = DistanceUtil.getDistance(rpbList.get(hasAdd-1).getPoint(), point);
								if (distance > 100 ) {
									hasAdd++;
								//	pointList.add(point);
									
									rpb.setDirect(rootResults.getJSONObject(i).getInt("Direct"));
									rpb.setLat(mLat);
									rpb.setLng(mLon);
									rpb.setSpeed(rootResults.getJSONObject(i).getDouble("Speed"));
									rpb.setPoint(point);
									rpbList.add(rpb);
								} else {
									continue;
								}
							}
							// point = CoordinateConvert.fromWgs84ToBaidu(point);
							// //纠正经纬度偏差
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
					Log.d(TAG, "把历史轨迹点装入pointList中时，抛出JSONException");
				}
	}
	
	/**
	 * 根据filterForRootJson绘制好的pointList历史轨迹点数据绘制历史轨迹
	 */
	public void makeReplayPath() {
		// ProgrammingPlace2
		// 添加一个自定义覆盖层，以箭头表示每个历史点
		
		//在绘制图层之前，先清理一下
		mMapView.getOverlays().clear();
		/**
		 * 几何图形覆盖层
		 */
		GraphicsOverlay graphicsOverlay = new GraphicsOverlay(mMapView);
		mMapView.getOverlays().add(graphicsOverlay);
		/**
		 * 自定义覆盖层
		 */
		// 准备overlay图像数据，根据实情情况修复
		Drawable greenMark = getResources()
				.getDrawable(R.drawable.history_direction_48);
		ArrowsPointOverlay arrowsOverlay = new ArrowsPointOverlay(greenMark,
				mMapView);
		mMapView.getOverlays().add(arrowsOverlay);

		Log.d(TAG, "有轨迹点" + rpbList.size());

		// 在地图上绘制出历史轨迹
	//	int ps = pointList.size();
		int rpbSize = rpbList.size();
		// OverlayItem item = null;
		for (int i = 0; i < rpbSize; i++) {
			if (i == 0) {
				// 添加点
				OverlayItem item = new OverlayItem(rpbList.get(i).getPoint(),
						"item" + i, "item" + i);
				item.setMarker(getResources().getDrawable(R.drawable.history_st));
				arrowsOverlay.addItem(item);

				graphicsOverlay.setData(drawPoint(rpbList.get(i).getPoint()));
				// 移动，缩放地图到最视野
				mMapController.setZoom(16);
				mMapController.setCenter(rpbList.get(i).getPoint());
				mMapView.refresh();
				mMapView.invalidate();

			} else if (i > 0 && i < rpbSize-1) {

				graphicsOverlay.setData(drawLine(rpbList.get(i-1).getPoint(),rpbList.get(i).getPoint()));
				// 添加点
				// graphicList.add(drawPoint(pointList.get(i)));
				graphicsOverlay.setData(drawPoint(rpbList.get(i).getPoint()));

				OverlayItem item = new OverlayItem(rpbList.get(i).getPoint(),
						"item" + i, "item" + i);

				item.setMarker(getResources().getDrawable(
						selectArrowId(rpbList.get(i).getDirect())));
				item.setAnchor(OverlayItem.ALING_CENTER);
				
				arrowsOverlay.addItem(item);
				

				// 移动，缩放地图到最视野
				mMapController.setZoom(16);
				mMapController.setCenter(rpbList.get(i).getPoint());

				mMapView.refresh();
				mMapView.invalidate();

				Log.d(TAG, "自定义覆盖层的点数" + arrowsOverlay.size());
			}
			else {
				graphicsOverlay.setData(drawLine(rpbList.get(i-1).getPoint(),
						rpbList.get(i).getPoint()));
				// 添加点
				// graphicList.add(drawPoint(pointList.get(i)));
				graphicsOverlay.setData(drawPoint(rpbList.get(i).getPoint()));

				OverlayItem item = new OverlayItem(rpbList.get(i).getPoint(),
						"item" + i, "item" + i);
				
				item.setMarker(getResources().getDrawable(R.drawable.history_en));
				arrowsOverlay.addItem(item);

				// 移动，缩放地图到最视野
				mMapController.setZoom(16);
				mMapController.setCenter(rpbList.get(rpbSize-1).getPoint());

				mMapView.refresh();
				mMapView.invalidate();
				
			}
		}
	}

	/**
	 * 绘制折线，该折线状态随地图状态变化
	 * 
	 * @return 折线对象
	 */
	public Graphic drawLine(GeoPoint stp, GeoPoint enp) {
		// 构建线
		Geometry lineGeometry = new Geometry();
		// 设定折线点坐标
		GeoPoint[] linePoints = new GeoPoint[2];
		linePoints[0] = stp;
		linePoints[1] = enp;
		// linePoints[2] = pt3;
		lineGeometry.setPolyLine(linePoints);
		// 设定样式
		Symbol lineSymbol = new Symbol();
		Symbol.Color lineColor = lineSymbol.new Color();
		lineColor.red = 255;
		lineColor.green = 0;
		lineColor.blue = 0;
		lineColor.alpha = 255;
		lineSymbol.setLineSymbol(lineColor, 4);
		// 生成Graphic对象
		Graphic lineGraphic = new Graphic(lineGeometry, lineSymbol);
		// graphicPathList.add(lineGraphic);
		return lineGraphic;
	}

	/**
	 * 绘制单点，该点状态不随地图状态变化而变化
	 * 
	 * @return 点对象
	 */
	public Graphic drawPoint(GeoPoint point) {
		// 构建点
		Geometry pointGeometry = new Geometry();
		// 设置坐标
		pointGeometry.setPoint(point, 4); // geoPoint - 地理坐标（百度经纬度),pixel -
											// 点的像素大小
		// 设定样式
		Symbol pointSymbol = new Symbol();
		Symbol.Color pointColor = pointSymbol.new Color();
		pointColor.red = 0;
		pointColor.green = 126;
		pointColor.blue = 255;
		pointColor.alpha = 255;
		pointSymbol.setPointSymbol(pointColor);
		// 生成Graphic对象
		Graphic pointGraphic = new Graphic(pointGeometry, pointSymbol);
		// graphicPathList.add(pointGraphic);
		return pointGraphic;
	}
	
	/**
	 * 自定义图层，显示轨迹点箭头
	 */
	class ArrowsPointOverlay extends ItemizedOverlay<OverlayItem> 
	{

		public ArrowsPointOverlay(Drawable mark, MapView mapView) {
			super(mark, mapView);
		}

		@Override
		public boolean onTap(GeoPoint pt, MapView mapView) {
			// 处理MapView的点击事件，当返回true时
			//return super.onTap(arg0, arg1);
			  super.onTap(pt,mapView);  
              return false; 
		}

		@Override
		protected boolean onTap(int index) {
			// 处理item点击事件
			//return super.onTap(arg0);
	        System.out.println("item onTap: "+index); 
	        showPointInfoDialog(index);
	        return true;
		}
	}
	
	/**
	 * 显示历史轨迹点详细信息
	 * @param index
	 */
	public void showPointInfoDialog(int index)
	{
		Log.d(TAG, "show pointInfo Dialog");
		/**获取引用edittext.xml配置文件中的视图组件*/
		LayoutInflater inflater = (LayoutInflater) PlayBackHistoryPathActivity.this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		final View view = inflater.inflate(R.layout.dialog_show_point_info,
				null);
		/**
		 * 获取所有控件
		 */
		TextView showTime = (TextView) view.findViewById(R.id.show_time_text);
		TextView showSpeed = (TextView) view.findViewById(R.id.show_speed_text);
		TextView showLat = (TextView) view.findViewById(R.id.show_lat_text);
		TextView showLon = (TextView) view.findViewById(R.id.show_lon_text);
		
		if(showTime != null && showSpeed != null &&
				showLat != null && showLon != null )
		{
			ReplayPathBean rpb = rpbList.get(index);
			
			showTime.setText(rpb.getCollectTime());
			showSpeed.setText(rpb.getSpeed().toString());
			showLat.setText(rpb.getLat().toString());
			showLon.setText(rpb.getLng().toString());
		}
		
		
		/** 这里使用链式写法创建了一个AlertDialog对话框,并且把应用到得视图viwe放入到其中 */

		/** 添加AlertDialog的用户登录按钮,并且设置按钮响应事件 */
		new AlertDialog.Builder(PlayBackHistoryPathActivity.this)
				.setTitle("点" + index+1 + " 的详细信息")
				.setView(view)
				.setNegativeButton("关闭",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0,
									int arg1) {
								/*Toast.makeText(TestThreadActivity.this, "取消播放",
										Toast.LENGTH_LONG).show();*/
							}
						}).show();
	}
	
	/**
	 * 触发弹出对话框，选择起止日期
	 *
	 */
	class MyButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			
			switch (v.getId()) {
			case R.id.play_path_button: //播放历史轨迹点
				Log.d(TAG, "click to replay button" + v.getId());
				if (stDateTime != null && enDateTime != null) {
					// 若pointList轨迹点集合已经存在，则直接播放轨迹点
					if (rpbList != null && rpbList.size() > 0) {
						makeReplayPath();
					}
					// 若pointList轨迹点集合为空，则弹出填写时间的对话框，填写时间，请求接口的规矩点数据
					else if (rpbList == null) {
						showSetTimeDialog();
					}
				}
				else {
					showSetTimeDialog();
				}
				break;
			case R.id.set_time_button:  //设置起始时间
				Log.d(TAG, "click to setTime button");
				showSetTimeDialog();
				break;
			case R.id.back_button:  //返回到车辆列表
				/*Intent myIntent = null;  
	            myIntent = new Intent(PlayBackHistoryPathActivity.this, CarListActivity.class);  
	            startActivity(myIntent); */ 
				mMapView.getOverlays().clear();
	            PlayBackHistoryPathActivity.this.finish(); 
				break;
			default:
				//showSetTimeDialog();
				break;
			}

		}
	}
	
	public void showSetTimeDialog()
	{
		Log.d(TAG, "show setTime Dialog");
		/**获取引用edittext.xml配置文件中的视图组件*/
		LayoutInflater inflater = (LayoutInflater) PlayBackHistoryPathActivity.this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		final View view = inflater.inflate(R.layout.dialog_set_date_time,
				null);
		calendar = Calendar.getInstance();//获得Calendar对象
		
		/**
		 * 获取所有控件
		 */
		stDateEditor = (EditText) view.findViewById(R.id.set_st_date_edit);
		stTimeEditor = (EditText) view.findViewById(R.id.set_st_time_edit);
		
		enDateEditor = (EditText) view.findViewById(R.id.set_en_date_edit);
		enTimeEditor = (EditText) view.findViewById(R.id.set_en_time_edit);
		
		if(stDateEditor != null && stTimeEditor != null &&
				enDateEditor != null && enTimeEditor != null )
		{
			/**
			 * 在Edit中绑定焦点监听器
			 */
			//设置开始时间日期的Edit
			stDateEditor.setOnFocusChangeListener(new MyDateEditOnFocusListener());
			stTimeEditor.setOnFocusChangeListener(new MyTimeEditOnFocusListener());
			//设置终止时间日期的Edit
			enDateEditor.setOnFocusChangeListener(new MyDateEditOnFocusListener());
			enTimeEditor.setOnFocusChangeListener(new MyTimeEditOnFocusListener());
			
			/**
			 * 设置EditText始终不弹出软件键盘
			 */
			stDateEditor.setInputType(InputType.TYPE_NULL);
			stTimeEditor.setInputType(InputType.TYPE_NULL);
			enDateEditor.setInputType(InputType.TYPE_NULL);
			enTimeEditor.setInputType(InputType.TYPE_NULL);
		}
		
		
		/** 这里使用链式写法创建了一个AlertDialog对话框,并且把应用到得视图viwe放入到其中 */

		/** 添加AlertDialog的用户登录按钮,并且设置按钮响应事件 */
		new AlertDialog.Builder(PlayBackHistoryPathActivity.this)
				.setTitle("起止时间")
				.setView(view)
				.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0,
									int arg1) {
								Log.d(TAG, "before dismiss");
								arg0.dismiss();
								Log.d(TAG, "after dismiss");
								stDateTime = stDateEditor.getText()
										.toString()
										+ " "
										+ stTimeEditor.getText().toString();
								enDateTime = enDateEditor.getText()
										.toString()
										+ " "
										+ enTimeEditor.getText().toString();
								Log.d(TAG, "after dismiss run to here!!");
							//	requestReplayPath(null, stDateTime, enDateTime, "baidu", null);
								/**
								 * 启动子线程完成请求，准备点等操作
								 */
								Log.d(TAG, "before start the thread is "+  Thread.currentThread().getName());
								RequestToHistoryThread request = new RequestToHistoryThread(mHandler, IMEI, stDateTime, enDateTime);
								request.start();
								
								Log.d(TAG, "after dismiss and statrThread run to here!!");
							}
							/** 添加对话框的退出按钮,并且设置按钮响应事件 */
						})
				.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0,
									int arg1) {
								Toast.makeText(PlayBackHistoryPathActivity.this, "取消播放",
										Toast.LENGTH_LONG).show();
							}
						}).show();
	}
	
	/**
	 * 为EditText绑定监听器，点击弹出日期选择对话框
	 * 移植到其他地方，要更改控件的ID，因为是根据控件的ID，
	 * 判断内容会写到那个控件的
	 */
	private class MyDateEditOnFocusListener implements
			View.OnFocusChangeListener {

		@Override
		public void onFocusChange(final View dateEdit, boolean hasFocus) {
			if (hasFocus) {
				new DatePickerDialog(PlayBackHistoryPathActivity.this,
						new DatePickerDialog.OnDateSetListener() {

							@Override
							public void onDateSet(DatePicker view, int year,
									int monthOfYear, int dayOfMonth) {
								calendar.set(year, monthOfYear, dayOfMonth);
								if (dateEdit != null
										&& dateEdit.getId() == R.id.set_st_date_edit) {
									// stTimeStr = monthOfYear +
									// "/"+dayOfMonth+"/"+year;
									/**
									 * 设置日期的值为日期控件显示的值 将日期在TextView中显示，月份要加1
									 */
									stDateEditor.setText(bulingTools(year + "")
											+ "-"
											+ bulingTools(monthOfYear+1 + "")
											+ "-"
											+ bulingTools(dayOfMonth + ""));
									stDateEditor.clearFocus();
								} else if (dateEdit != null
										&& dateEdit.getId() == R.id.set_en_date_edit) {
									// enTimeStr = monthOfYear +
									// "/"+dayOfMonth+"/"+year;
									enDateEditor.setText(bulingTools(year + "")
											+ "-"
											+ bulingTools(monthOfYear+1 + "")
											+ "-"
											+ bulingTools(dayOfMonth + ""));
									enDateEditor.clearFocus();
								}
							}
							
						}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar
								.get(Calendar.DAY_OF_MONTH)).show();
			}
		}

	}

	/**
	 * 为EditText绑定监听器，点击弹出时间选择对话框
	 * 移植到其他地方，要更改控件的ID，因为是根据控件的ID，
	 * 判断内容会写到那个控件的
	 */
	private class MyTimeEditOnFocusListener implements
			View.OnFocusChangeListener {
		@Override
		public void onFocusChange(final View timeEdit, boolean hasFocus) {
			if (hasFocus) {
				new TimePickerDialog(PlayBackHistoryPathActivity.this,
						new TimePickerDialog.OnTimeSetListener() {

							@Override
							public void onTimeSet(TimePicker view,
									int hourOfDay, int minute) {
								calendar.set(calendar.get(Calendar.YEAR),
										calendar.get(Calendar.MONTH),
										calendar.get(Calendar.DAY_OF_MONTH),
										hourOfDay, minute);

								enTimeEditor.setText(hourOfDay + ":" + minute);
								if (timeEdit != null
										&& timeEdit.getId() == R.id.set_st_time_edit) {
									// stTimeStr = monthOfYear +
									// "/"+dayOfMonth+"/"+year;
									/**
									 * 设置日期的值为日期控件显示的值 将日期在TextView中显示，月份要加1
									 */
									stTimeEditor.setText(bulingTools(hourOfDay
											+ "")
											+ ":" + bulingTools(minute + "")+ ":00");
									stTimeEditor.clearFocus();
								} else if (timeEdit != null
										&& timeEdit.getId() == R.id.set_en_time_edit) {
									// enTimeStr = monthOfYear +
									// "/"+dayOfMonth+"/"+year;
									enTimeEditor.setText(bulingTools(hourOfDay
											+ "")
											+ ":" + bulingTools(minute + "")+ ":00");
									enTimeEditor.clearFocus();
								}
							}
						}, calendar.get(Calendar.HOUR_OF_DAY), Calendar.MINUTE, true)
						.show();
			}
		}
	}
	
	/**
	 * 根据轨迹点的Direct，选择箭头图片
	 * @param direction
	 * @return
	 */
	private int selectArrowId(int direction) {
		int arrowId = R.drawable.history_direction_48;
		if(direction>=0 && direction <22.5 ){
			arrowId = R.drawable.history_direction_48;
		}
		else if (direction >=22.5 && direction < 67.5) {
			arrowId = R.drawable.history_direction_48_45;
		}
		else if (direction >=67.5 && direction < 112.5) {
			arrowId = R.drawable.history_direction_48_90;
		}
		else if (direction >=112.5 && direction < 157.5) {
			arrowId = R.drawable.history_direction_48_135;
		}
		else if (direction >=157.5 && direction < 202.5) {
			arrowId = R.drawable.history_direction_48_180;
		}
		else if (direction >=202.5 && direction < 247.5) {
			arrowId = R.drawable.history_direction_48_225;
		}
		else if (direction >=247.5 && direction < 292.5) {
			arrowId = R.drawable.history_direction_48_270;
		}
		else if (direction >=292.5 && direction < 337.5) {
			arrowId = R.drawable.history_direction_48_315;
		}
		else if (direction >=337.5 && direction <= 360) {
			arrowId = R.drawable.history_direction_48;
		}
		return arrowId;
	}
	
    /**
     * 为日期时间不够两位的，在前面补零
     * @param num
     * @return
     */
	private String bulingTools (String num)
	{
		StringBuffer two = new StringBuffer(num);
		if(two.length() == 1){
			two = two.insert(0, "0");
			return two.toString();
		}
		else if(two.length() > 1)
			return num;
		else{
			num = "00";
			return num;
		}
	}
	
	 /** 
     * 显示Toast消息 
     * @param msg 
     */  
    private void showToast(String msg){  
        if(mToast == null){  
            mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);  
        }else{  
            mToast.setText(msg);  
            mToast.setDuration(Toast.LENGTH_SHORT);
        }  
        mToast.show();  
    }
    
    /**
     * Activity生命周期管理函数
     */
    @Override
	protected void onDestroy(){
    	    mMapView.getOverlays().clear();
	      //  mMapView.destroy();
	     /*   if(mBMapMan!=null){
	                mBMapMan.destroy();
	                mBMapMan=null;
	        }*/
	        super.onDestroy();
	}
	@Override
	protected void onPause(){
	        mMapView.onPause();
	        if(mBMapMan!=null){
                mBMapMan.stop();
	        }
	        super.onPause();
	}
	@Override
	protected void onResume(){
	        mMapView.onResume();
	        mMapView.getOverlays().clear();
	        if(mBMapMan!=null){
	                mBMapMan.start();
	        }
        super.onResume();
	}
	
	//Activity生命周期管理函数结束
	
}
